package com.jml.dubbo.server.registr;

import java.net.URLEncoder;

import org.I0Itec.zkclient.ZkClient;

public class ServiceRegistrationImpl implements ServiceRegistration {
    /**
     * zk连接地址
     */
    private final String zkServers = "127.0.0.1";
    /**
     * 会话时间
     */
    private final int connectionTimeout = 5000;
    /***
     * zkClient
     */
    private ZkClient zkClient;


    private String rootNamePath = "/jml_rpc";

    public ServiceRegistrationImpl() {
        // 1. 连接zk连接
        zkClient = new ZkClient(zkServers, connectionTimeout);
    }


    /**
     *
     * @param serviceName   com.jml.UserService com.jml.api.UserService
     * @param serviceAddres jml://
     */
    @Override
    public void registr(String serviceName, String serviceAddres) {
        // 创建我们的根路径 jml_rpc
        if (!zkClient.exists(rootNamePath)) {
            zkClient.createPersistent(rootNamePath);
        }
        // 创建我们的接口路径 /jml_rpc/com.jml.UserService
        String serviceNodePath = rootNamePath + "/" + serviceName;
        if (!zkClient.exists(serviceNodePath)) {
            zkClient.createPersistent(serviceNodePath);
        }
        // 创建我们服务地址目录  /jml_rpc/com.jml.UserService+"/providers"
        String providerNodePath = serviceNodePath + "/" + "providers";
        if (!zkClient.exists(providerNodePath)) {
            zkClient.createPersistent(providerNodePath);
        }
        //创建我们服务地址 jml://192.168.11.11:8080/com.jml.sercice.UserSercice getUser
        String serviceAddresNodePath = providerNodePath + "/" + URLEncoder.encode(serviceAddres);
        System.out.println("serviceAddresNodePath:" + serviceAddresNodePath);
        if (zkClient.exists(serviceAddresNodePath)) {
            zkClient.delete(serviceAddresNodePath);
        }
        zkClient.createEphemeral(serviceAddresNodePath);
    }
    // 服务着注册（半个小时）、消费者（40分钟）、负载均衡 （20分钟）
}
